﻿// -----------------------------------------------------------------------
// <copyright file="BinaryHandler.cs" company="Microsoft">
// Processing image files
// </copyright>
// -----------------------------------------------------------------------
namespace WebServer.BusinessLogic.Handlers
{
    using WebServer.BusinessLogic.Handlers.Interface;

    /// <summary>
    /// handles binary requests.
    /// </summary>
    public class BinaryHandler : Handler
    {
        /// <summary>
        /// interface for testing
        /// </summary>
        private IFileSystemProvider fileSystemProvider;

        /// <summary>
        /// Initializes a new instance of the <see cref="BinaryHandler" /> class using IFileSystemProvider interface
        /// </summary>
        /// <param name="fs">fake interface for testing</param>
        public BinaryHandler(IFileSystemProvider fs)
        {
            this.fileSystemProvider = fs;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="BinaryHandler" /> class.
        /// </summary>
        public BinaryHandler()
        {
            this.fileSystemProvider = new FileSystemProvider();
        }

        /// <summary>
        /// Tries to handle request.
        /// </summary>
        /// <param name="request">
        /// The request.
        /// </param>
        /// <returns>
        /// The WebServer.BusinessLogic.Response.
        /// </returns>
        public override Response Handle(Request request)
        {
            string ext = request.HttpPath.ToLower();
            if (ext.EndsWith(".png") || ext.EndsWith(".jpg")
                || ext.EndsWith(".jpeg") || ext.EndsWith(".gif"))
            {
                string filePath = Configurator.Instance.RelativeWwwPath + request.HttpPath.Replace("/", "\\");

                if (!this.fileSystemProvider.FileExists(filePath))
                {
                    return this.NextHandler.Handle(request);
                }

                byte[] data = this.fileSystemProvider.GetDataOrFile(request.HttpPath, filePath);

                Response toReturn = new Response();
                toReturn.Data = data;

                // tuReturn.Data = Encoding.ASCII.GetBytes(filePath);
                toReturn.MimeType = BinaryHandler.IdentifyContentType(request);
                return toReturn;
            }

            return this.NextHandler.Handle(request);
        }
    }
}
